package mygang.dao.manager;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import mygang.dao.AbstractDAO;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

/**
 *
 * @author Volodymyr Lavrynovych <volodya.lavrynovych@gmail.com>
 * date: 25/02/2013
 */
@Component
public class AbstractManageDAO<E> extends AbstractDAO implements ManagerInterface<E> {

    private static final Logger log = Logger.getLogger(AbstractManageDAO.class.toString());
    
    public List<E> getAll() {
        log.debug("get all "+getGenericClass().getName());
        return (List<E>) getHibernateTemplate().loadAll(getGenericClass());
    }

    public void save(E obj) {
        log.debug("save "+getGenericClass().getName());
        getHibernateTemplate().saveOrUpdate(obj);
    }

    public void delete(long id) {
        log.debug("delete "+getGenericClass().getName()+" by id = "+id);
        getHibernateTemplate().delete(getById(id));
    }

    public E getById(long id) {
        log.debug("get "+getGenericClass().getName()+" by id = "+id);
        return (E) getHibernateTemplate().get(getGenericClass(), id);
    }
    
    /**
     * Returns Class of the generic object
     * source: http://www.velocityreviews.com/forums/t150143-generics-and-getclass.html
     * 
     * @return Class of the generic object
     */
    private Class getGenericClass() {
        Class result = null;
        Type type = this.getClass().getGenericSuperclass();

        if(type instanceof ParameterizedType){
            ParameterizedType pt = (ParameterizedType) type;
            Type[] fieldArgTypes = pt.getActualTypeArguments();
            result = (Class) fieldArgTypes[0];
        }
        return result;
    }
}